const {Sequelize ,DataTypes} = require("sequelize")
const {database,password,dialect,host,username} = require("./config");


//定义一个sequelize实例
const sequelize = new Sequelize(database,username,password,{
    host :host,
    dialect :dialect
})


//创建函数包装模型统一定义

function defineModel(name ,attar){
    //定义一个prop变量
    let prop ={};

    prop.id ={
        type :DataTypes.BIGINT,
        primaryKey:true,
        autoIncrement:true
    }
    prop.verious ={
        type: DataTypes.BIGINT,
        allowNull :false
    }
    prop.ceatedAt ={
        type:DataTypes.DATE,
        allowNull :false
    }
    prop.updatedAt ={
        type:DataTypes.DATE,
        allowNull: false 
    }
    
    //将外部定义的字段添加进来

    for(let key in attar){
        let value = attar[key];
        prop[key] = value
    }


    //真正利用sequelize实例定义一个模型方式

    let obj = sequelize.define(name,prop,{
        timestamps :false , //不会自动生成createdAt与updatedAt
        tableName :name ,  //指定表名称为模型名称
        

        //勾子对象
        hooks :{
            //生命周期函数用来检测在插入或者更新数据之前进行的验证
            beforeValidate :function(obj){
                let now = Date.now();
                //当第一次插入数据时
                if(obj.isNewRecord){
                    obj.ceatedAt = now ,
                    obj.updatedAt = now ,
                    obj.verious = 1 
                }else{
                    obj.updatedAt = now ,
                    obj.verious +=1 
                }

            }
        }
    })
    return obj ;

}

let obj = {
    sequelize ,
    defineModel ,
    DataTypes
}

module.exports = obj ;